package com.DHH.Controller.Device;

import com.DHH.BikeAction.BikeResult;
import com.DHH.BikeAction.BikeUnlockResult;
import com.DHH.BikeAction.DHHRequest;
import com.DHH.Config.DHHConstant;
import com.DHH.Dto.FilterQuery;
import com.DHH.Dto.Message;
import com.DHH.Dto.PageInfo;
import com.DHH.Dto.QueryInfo;
import com.DHH.Entity.Device.BikeLatest;
import com.DHH.Entity.Device.Device;
import com.DHH.Entity.Device.DeviceArea;
import com.DHH.Entity.Device.Dmap;
import com.DHH.Mapper.Device.BikeLatestMapper;
import com.DHH.Mapper.Device.DeviceAreaMapper;
import com.DHH.Mapper.Device.DeviceMapper;
import com.DHH.Mapper.Device.DmapMapper;
import com.DHH.Util.ReflectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * Created by Administrator on 2017/4/15.
 */
@Controller
@RequestMapping("Admin/Device/BikeLatest")
public class BikeLatestController {
    private Logger logger= LoggerFactory.getLogger(BikeLatestController.class);
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private BikeLatestMapper bikeLatestMapper;
    @Autowired
    private DmapMapper dmapMapper;

    @RequestMapping("/listPage")
    public String listPage(HttpSession session,ModelMap modelMap){

        return "admin/bikeLatest/listBikeLatestPage.jsp";
    }

    @RequestMapping("/listPageMini")
    public String listPageMini(HttpSession session,ModelMap modelMap){

        return "admin/bikeLatest/listBikeLatestPageMini.jsp";
    }

    @RequestMapping("/updatePage")
    public String updatePage(HttpSession session,Integer id,ModelMap modelMap)
    {
        if(id!=null)
        {
            BikeLatest bikeLatest=new BikeLatest();
            bikeLatest.setId(id);
            modelMap.put("bikeLatest",dmapMapper.selectByPrimaryKey(bikeLatest));
        }
        return "admin/bikeLatest/updateBikeLatestPageMini.jsp";
    }

    @RequestMapping("/update")
    public String update(HttpSession session,@RequestParam("id") Integer id,@RequestParam("udid") String udid,
                         @RequestParam("dhhid") String dhhid,@RequestParam("area") String area,
                         ModelMap modelMap)
    {
        if(id!=null)
        {
            Dmap dmap=new Dmap();
            dmap.setId(id);
            dmap.setUdid(udid);
            dmap.setDhhid(dhhid);
            dmap.setArea(area);
            modelMap.put("bikeLatest",dmapMapper.updateByPrimaryKey(dmap));
        }
        return "admin/bikeLatest/updateBikeLatestPageMini.jsp";
    }

    @RequestMapping("/curLocation")
    public String curLocation(String id,HttpSession session,ModelMap modelMap){
        Device device=new Device();
        Example example=new Example(Device.class);
        example.createCriteria().andEqualTo("udid",id);
        device=deviceMapper.selectByExample(example).get(0);
        if(Double.parseDouble(device.getLat())==0.0&&Double.parseDouble(device.getLng())==0.000){
            device.setLat(Double.toString(device.getGsmLat()));
            device.setLng(Double.toString(device.getGsmLng()));
        }
        modelMap.put("device",device);
        return "admin/bikeLatest/curLocation.jsp";
    }

    @RequestMapping("/detailsPage")
    public String detailPage(HttpSession session,@RequestParam Integer id,ModelMap modelMap)
    {
        return "admin/device/detailsDevicePage.jsp";
    }
    @ResponseBody
    @RequestMapping("/query")
    public PageInfo<BikeLatest> query(QueryInfo queryInfo) {
        System.err.println("--------------查询参数---------------");
        System.err.println(queryInfo);
        System.err.println("--------------查询参数---------------");
        /*为查询设置统一分页条件和排序条件*/
        PageHelper.startPage(queryInfo.getCurrentPage(), queryInfo.getPageSize());
        //PageHelper.orderBy(queryInfo.getSort() + " " + queryInfo.getOrder());
        if(queryInfo.getType()==null)
        {
            queryInfo.setType("search");
        }
        if(queryInfo.getCurrentPage()==null)
        {
            queryInfo.setCurrentPage(1);
        }
        if(queryInfo.getPageSize()==null)
        {
            queryInfo.setPageSize(10);
        }
        try{
            if(queryInfo.getType().equals("screen"))
            {
                return this.screen(queryInfo);
            }
            if(queryInfo.getType().equals("filter"))
            {

                return this.searchFilter(queryInfo);
            }
            return this.search(queryInfo);
        }catch (Exception e)
        {
            PageInfo<BikeLatest> p=new PageInfo<BikeLatest>();
            e.printStackTrace();
            p.setMsg("查询失败，请稍后重试！");
            return p;
        }

    }



    /**
     * 查询
     * @param queryInfo
     * @return
     */
    private PageInfo<BikeLatest> search(QueryInfo queryInfo)
    {   System.out.println("---------\n"+queryInfo);
        BikeLatest bikeLatest=new BikeLatest();
            /*在这里设置相关的查询参数*/
        PageInfo<BikeLatest> pageInfo =new PageInfo<BikeLatest>();
        if(!queryInfo.getSearchKey().equals(""))
        {
            bikeLatest.setUdid(queryInfo.getSearchKey());
        }
        Page<BikeLatest> page = (Page<BikeLatest>) bikeLatestMapper.selectBike(bikeLatest);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
        return pageInfo;
    }

    /**
     * 筛选
     * @param queryInfo
     * @return
     */
    private  PageInfo<BikeLatest> screen(QueryInfo queryInfo) {
        PageInfo<BikeLatest> pageInfo=new PageInfo< BikeLatest>();
        BikeLatest bikeLatest=new  BikeLatest();
        for (String key : queryInfo.getMap().keySet()) {
            if(queryInfo.getMap().get(key)!=null&&!queryInfo.getMap().get(key).equals(""))
            {
                ReflectionUtils.setFieldValue(bikeLatest,key,queryInfo.getMap().get(key));
            }
        }
        Page<BikeLatest> page = (Page<BikeLatest>) bikeLatestMapper.selectBike(bikeLatest);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
        return pageInfo;
    }

    /**
     * 过滤
     * @param queryInfo
     * @return
     */
    private PageInfo<BikeLatest> searchFilter(QueryInfo queryInfo) throws ParseException {

        PageInfo<BikeLatest> pageInfo=new PageInfo< BikeLatest>();
        FilterQuery filterQuery = new FilterQuery();
        filterQuery.setStartValue(queryInfo.getFilterStartValue());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        filterQuery.setEndValue(sdf.format(new Date(sdf.parse(queryInfo.getFilterEndValue()).getTime() + 24 * 3600 * 1000)));
        Page<BikeLatest> page = (Page<BikeLatest>)bikeLatestMapper.filterByBikeLatest(filterQuery);
        pageInfo.setRows(page.getResult());
        pageInfo.setTotalRow(page.getTotal());
        pageInfo.setCurrentPage(queryInfo.getCurrentPage());
        return pageInfo;
    }

    @ResponseBody
    @RequestMapping("/bikeAction")
    public Message bikeAction(String device_id,Integer action){
        Message message=new Message();
       try{
           DHHRequest dhhRequest=new DHHRequest();
           switch(action)
           {

               case 1:
                   dhhRequest.setCtl(DHHConstant.API_ctl_action1);
                   break;
               case 2:
                   dhhRequest.setCtl(DHHConstant.API_ctl_action2);
                   break;
               case 3:
                   dhhRequest.setCtl(DHHConstant.API_ctl_action3);
                   break;
               case 4:
                   dhhRequest.setCtl(DHHConstant.API_ctl_action4);
                   break;
               case 5:
                   dhhRequest.setCtl(DHHConstant.API_ctl_action5);
                   break;
               case 6:
                   dhhRequest.setCtl(DHHConstant.API_ctl_action6);
                   break;

           }
           dhhRequest.setUdid(device_id);
           BikeResult bikeResult=dhhRequest.baseRequest();
           if(bikeResult.getCode().equals("200")){
               message.setState(true);
               message.setMsg("指令下达成功");
           }else{
               message.setState(false);
               message.setMsg(bikeResult.getCode());
           }
       }catch (Exception e){
           message.setState(false);
           message.setMsg(e.getMessage());
       }
        return  message;
    }


}

